from django.http import JsonResponse, HttpResponse
from rest_framework.views import  APIView
from api.models import UserInfo

from api.utils.jwt_createa_and_verified import create_token
from api.utils.current_limiting import VisitLimit

order_dict = {
    1:{
        'name':"ipone5",
        'xinghao':"plus",
        "price":5500,
    },
    2: {
        'name': "ipone8",
        'xinghao': "pro",
        "price": 8800,
    }

}


class AuthView(APIView):
    """用于用户登录认证，来就给你token，下次拿token去请求另外的接口就认你登录了"""
    authentication_classes = []
    permission_classes = []
    throttle_classes = [VisitLimit,]

    def post(self,request,*args,**kwargs):
        user = request.data.get('username')
        pwd = request.data.get('password')
        try:
            user_obj = UserInfo.objects.filter(username=user,password=pwd).first()
            if not user_obj:
                return JsonResponse({'code':1002,'msg':'用户名或密码错误'})
            token =  create_token(user_obj.id,user_obj.username)
            # 用户登录成功，返回这个用户的token
            return JsonResponse({'code':1000,'msg':'登录成功','token':token})
        except:
            return JsonResponse({'code':1001,'msg':'用户登陆异常'})


class OrderView(APIView):
    """这是用于订单相关业务
    只有svip有权限
    """
    def get(self,request,*args,**kwargs):
        # 用try模式可以免去很多基础数据校验，如不完整或传递参数类型有问题
        try:
            return JsonResponse({'code':2000,'msg':'返回订单信息成功','order_dict':order_dict})
        except:
            return JsonResponse({'code':2001,'msg':'获取订单异常'})


class UserInfoView(APIView):
    """
    普通用户，vip有权限
    """
    def get(self,request,*args,**kwargs):
        return JsonResponse({'code':3000,'msg':'用户信息返回成功'})